package com.wrupple.muba.catalogs.client.activity.process.impl;

import java.util.List;

import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.wrupple.muba.catalogs.client.activity.process.CatalogSelectionProcess;
import com.wrupple.muba.catalogs.client.activity.process.CatalogTypeSelectionProcess;
import com.wrupple.muba.catalogs.client.activity.process.UniversalCatalogSelectionProcess;
import com.wrupple.muba.catalogs.client.cms.service.CatalogManagementSystem;
import com.wrupple.muba.catalogs.domain.CatalogEntry;
import com.wrupple.muba.catalogs.domain.CatalogPlace;
import com.wrupple.muba.catalogs.domain.CatalogProcessDescriptor;
import com.wrupple.muba.catalogs.domain.JsCatalogKey;
import com.wrupple.muba.common.domain.DesktopPlace;
import com.wrupple.muba.common.domain.FilterData;
import com.wrupple.muba.common.shared.SequentialProcess;
import com.wrupple.muba.common.shared.State;
import com.wrupple.muba.common.shared.StateTransition;

public class UniversalCatalogSelectionProcessImpl extends
		SequentialProcess<Boolean, List<CatalogEntry>> implements UniversalCatalogSelectionProcess {

	boolean multiple;
	private CatalogManagementSystem cms;
	
	@Inject
	public UniversalCatalogSelectionProcessImpl(CatalogTypeSelectionProcess typeSelection, CatalogManagementSystem cms) {
		super();
		this.cms=cms;
		// read multiplicity
		add(new ReadMultiplicity());
		addAll(typeSelection);
		add(new Selection());
		add(new Consolidate());
	}
	
	class Consolidate implements State<Object,Object>{

		@Override
		public void start(Object parameter, StateTransition<Object> onDone,
				EventBus bus) {
			onDone.setResultAndFinish(parameter);
		}
		
	}

	class ReadMultiplicity implements State<Boolean, DesktopPlace>{

		@Override
		public void start(Boolean parameter,
				StateTransition<DesktopPlace> onDone, EventBus bus) {
			multiple = parameter;
			onDone.setResultAndFinish(null);
		}
		
	}
	
	class Selection implements State.ContextAware<List<CatalogPlace>,List<CatalogEntry>>{

		private Context context;

		@Override
		public void start(List<CatalogPlace> parameter,
				StateTransition<List<CatalogEntry>> onDone, EventBus bus) {
			String catalog = parameter.get(0).getCatalog();
			CatalogSelectionProcess<JsCatalogKey> process = cms.getContentManager(catalog).getSelectionProcess(multiple);
			CatalogProcessDescriptor input = new CatalogProcessDescriptor(new FilterData(), catalog, null);
			
			
			StateTransition onDoneCast = onDone;
			context.getProcessManager().processSwitch(process, "UniversalSelection", input, onDoneCast, bus);
		}

		@Override
		public void setContext(
				com.wrupple.muba.common.shared.State.Context context) {
			this.context = context;
			
		}
	}

}
